package com.b.service.impl;

import com.b.domain.FavoriteVideo;
import com.b.domain.User;
import com.b.domain.Video;
import com.b.repository.FavoriteRepository;
import com.b.repository.FavoriteVideoRepository;
import com.b.repository.UserRepository;
import com.b.repository.VideoRepository;
import com.b.vo.Result;
import com.github.pagehelper.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import com.b.domain.Favorite;
import com.b.dao.FavoriteMapper;
import com.b.service.FavoriteService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Resource
    private FavoriteMapper favoriteMapper;
    @Resource
    private FavoriteRepository favoriteRepository;
    @Resource
    private FavoriteVideoRepository favoriteVideoRepository;
    @Resource
    private VideoRepository videoRepository;
    @Resource
    private UserRepository userRepository;

    @Override
    public int insert(Favorite record) {
        return favoriteMapper.insert(record);
    }

    @Override
    public int insertSelective(Favorite record) {
        return favoriteMapper.insertSelective(record);
    }

    @Override
    public List<Favorite> getAll() {
        return favoriteMapper.getAll();
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return favoriteMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Favorite selectByPrimaryKey(Integer id) {
        return favoriteMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Favorite record) {
        return favoriteMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Favorite record) {
        return favoriteMapper.updateByPrimaryKey(record);
    }

    @Override
    public Result favoriteListByUserId(Integer userId,String title) {
        //去es查询
        List<Favorite> esByUserId = favoriteRepository.findByUserId(userId);
        if (!esByUserId.isEmpty()) {
            ArrayList<Favorite> favorites = new ArrayList<>();
            List<Video> videoList = new ArrayList<>();
            for (Favorite favorite : esByUserId) {
                Integer id = favorite.getId();
                List<FavoriteVideo> favoriteVideos = favoriteVideoRepository.findByFavoriteId(id);
                if (!favoriteVideos.isEmpty()) {
                    for (FavoriteVideo favoriteVideo : favoriteVideos) {
                        Integer vid = favoriteVideo.getVideoId();
//                        Optional<Video> videoInfo = videoRepository.findById(vid);
                        Video videoInfo = videoRepository.findByIdAndTitleLike(vid,title);
                        //查找作者信息
                        //返回视频集合
                        /*if (videoInfo.isPresent()) {
                            Video video = videoInfo.get();
                            // 查询视频作者并设置到video中（与数据库结果一致：user仅在video内部）
                            Optional<User> authorOptional = userRepository.findById(video.getUserId());
                            authorOptional.ifPresent(video::setUser);
                            videoList.add(video);
                        }*/

                        User userById = userRepository.findUserById(videoInfo.getUserId());
                        videoInfo.setUser(userById);
                        videoList.add(videoInfo);
                        /*for (Video video : videoInfo) {
                            Optional<User> authorOptional = userRepository.findById(video.getUserId());
                            authorOptional.ifPresent(video::setUser);
                            videoList.add(video);
                        }*/
                    }
                    favorite.setVedioList(videoList); // 将包含作者的video设置到历史记录中
                    favorites.add(favorite);
                }else {
                    //没有相关视频,直接添加空表
                    favorites.add(favorite);
                }
            }
            return new Result().setCode("200").setMsg("es查询成功").setData(favorites);

        }else {//去数据库查询
            List<Favorite> favoriteVoList = favoriteMapper.findByUserId(userId,title);
            return new Result().setCode("200").setMsg("数据库查询成功").setData(favoriteVoList);
        }
    }

    @Override
    public Result favoritePageList(Integer userId, Integer curPage, Integer pageSize, Integer title) {
        System.out.println("userId = " + userId + ", curPage = " + curPage + ", pageSize = " + pageSize + ", title = " + title);
        try {
            PageRequest pageRequest = PageRequest.of(curPage, pageSize);
            Page<Favorite> favoritePageByUserId = favoriteRepository.findPageByUserId(userId, pageRequest);
            List<Video> videoList = new ArrayList<>();
            for (Favorite favorite : favoritePageByUserId) {
                Integer id = favorite.getId();
                Page<FavoriteVideo> pageByFavoriteId = favoriteVideoRepository.findPageByFavoriteId(id, pageRequest);
                for (FavoriteVideo favoriteVideo : pageByFavoriteId) {
                    Integer vid = favoriteVideo.getVideoId();
                    Optional<Video> videoInfo = videoRepository.findById(vid);
                    if (videoInfo.isPresent()) {
                        Video video = videoInfo.get();
                        Optional<User> authorOptional = userRepository.findById(video.getUserId());
                        authorOptional.ifPresent(video::setUser);
                        videoList.add(video);
                    }
                }
            }
            return new Result().setCode("200").setMsg("查询成功").setData(favoritePageByUserId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().setCode("500").setMsg("查询失败");
        }
    }

    @Override
    public Result saveFavorite(Favorite favorite) {
        //判断有无id
        try {
            if (favorite.getId()==null){//添加收藏夹
                favoriteMapper.insert(favorite);
                favoriteRepository.save(favorite);
            }
            return new Result().setCode("200").setMsg("添加成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().setCode("500").setMsg("添加失败!");
        }
    }
}

